package com.zbkj.crmeb.merchant.api.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.zbkj.crmeb.merchant.api.request.CantonFairInfoRequest;
import com.zbkj.crmeb.store.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.common.CommonResult;
import com.zbkj.crmeb.chant.request.AppletAccountRequest;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.front.response.IndexAdviceResponse;
import com.zbkj.crmeb.front.response.IndexInfoResponse;
import com.zbkj.crmeb.front.response.IndexProductBannerResponse;
import com.zbkj.crmeb.front.service.OrderService;
import com.zbkj.crmeb.front.vo.OrangeWechatAppletConfigVo;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.merchant.api.response.PickIngConfigResponse;
import com.zbkj.crmeb.merchant.api.service.MerIndexService;
import com.zbkj.crmeb.store.dto.HomeStyleDTO;
import com.zbkj.crmeb.store.model.ChannelStoreBrandConfig;
import com.zbkj.crmeb.store.model.HomeStyle;
import com.zbkj.crmeb.store.model.StoreBrand;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductMer;
import com.zbkj.crmeb.store.model.StoreZone;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户 -- 用户中心
 */
@RestController("MerIndexController")
@RequestMapping("api/front/mer")
@Api(tags = "首页")
@Slf4j
public class FontIndexController extends ApiBaseController {
    @Autowired
    private MerIndexService indexService;
    @Autowired
    private OrderService orderService;
    @Autowired
    HomeStyleService homeStyleService;
    @Autowired
    StoreBrandService storeBrandService;
    @Autowired
    ChannelStoreBrandConfigService channelStoreBrandConfigService;
    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;
    @Autowired
    private MerStoreProductService storeProductService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private StoreProductMerService storeProductMerService;
    @Autowired
    private CantonFairInfoService cantonFairInfoService;

    /**
     * 首页产品的轮播图和产品信息
     * @author Mr.Zhang
     * @since 2020-06-02
     */
    @ApiOperation(value = "首页产品的轮播图和产品信息")
    @RequestMapping(value = "/groom/list/{type}", method = RequestMethod.GET)
    @ApiImplicitParam(name = "type", value = "类型 【1 精品推荐 2 热门榜单 3 首发新品 4促销单品】", dataType = "int", required = true)
    public CommonResult<IndexProductBannerResponse> getProductBanner(@PathVariable(value = "type") int type, PageParamRequest pageParamRequest){
        if(type < Constants.INDEX_RECOMMEND_BANNER || type > Constants.INDEX_BENEFIT_BANNER){
            return CommonResult.validateFailed();
        }
        return CommonResult.success(indexService.getProductBanner(type, pageParamRequest));
    }


    /**
     * 首页数据
     * @author Mr.Zhang
     * @since 2020-06-02
     */
    @ApiOperation(value = "首页数据")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public CommonResult<IndexInfoResponse> getIndexInfo(HttpServletRequest servletRequest, PageParamRequest pageParamRequest){
        return CommonResult.success(indexService.getIndexInfo(getMerId(servletRequest), pageParamRequest));
    }
    
    /**
     * 热门搜索
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @ApiOperation(value = "热门搜索")
    @RequestMapping(value = "/search/keyword", method = RequestMethod.GET)
    public CommonResult<List<HashMap<String, Object>>> hotKeywords(HttpServletRequest request){
        return CommonResult.success(indexService.hotKeywords(getMerId(request)));
    }

    /**
     * 分享配置
     * @author Mr.Zhang
     * @since 2020-05-25
     */
    @ApiOperation(value = "分享配置")
    @RequestMapping(value = "/share", method = RequestMethod.GET)
    public CommonResult<HashMap<String, String>> share(HttpServletRequest servletRequest){
        return CommonResult.success(indexService.getShareConfig(getMerId(servletRequest)));
    }

    /**
     * 获取支付方式小程序配置
     * @param
     * @return 支付方式小程序配置
     */
    @ApiOperation(value = "获取支付方式小程序配置")
    @RequestMapping(value = "/orangeConfig", method = RequestMethod.GET)
    public CommonResult<OrangeWechatAppletConfigVo> getOrangeConfig(HttpServletRequest servletRequest){
        return CommonResult.success(orderService.getOrangeConfig(getMerId(servletRequest)));
    }

    /**
     * 查询首页推荐的品类与品牌
     * @author cyz
     * @since 2021-05-17
     */
    @ApiOperation(value = "首页数据")
    @RequestMapping(value = "/advice", method = RequestMethod.GET)
    public CommonResult<IndexAdviceResponse> getAdviceList(HttpServletRequest servletRequest){
        return CommonResult.success(indexService.getAdviceList(getMerId(servletRequest)));
    }

    /**
     * 专区列表
     * @author cyz
     * @since 2021-05-17
     */
    @ApiOperation(value = "专区列表")
    @RequestMapping(value = "/zone/list", method = RequestMethod.GET)
    public CommonResult<IndexAdviceResponse> getZoneList(HttpServletRequest servletRequest){
        return CommonResult.success(indexService.getZoneList(getMerId(servletRequest)));
    }

    @ApiOperation(value = "个性化首页样式")
    @GetMapping("/home/style/list")
    public CommonResult<List<HomeStyleDTO>> listHomeStyleEntity(HttpServletRequest request) {
        List<HomeStyle> list = homeStyleService.list(Wrappers.<HomeStyle>lambdaQuery()
                .eq(HomeStyle :: getMerId, getMerId(request))
                .isNull(HomeStyle :: getActivityId)
                .orderByAsc(HomeStyle :: getSort)
                );
        
        List<HomeStyleDTO> homeStyleDTO = new ArrayList<>();
        for(HomeStyle homeStyle : list) {
            HomeStyleDTO dto = new HomeStyleDTO();
            BeanUtils.copyProperties(homeStyle, dto);
            dto.setType(homeStyle.getType().getValue());
            dto.setPosition(JSON.parseObject(homeStyle.getPosition()));
            dto.setParame(JSON.parseObject(homeStyle.getParame()));
            dto.setStyle(JSON.parseObject(homeStyle.getStyle()));
            //小程序商品展示需要过滤已售罄商品
            if (Objects.equals(dto.getType(),5)){
                List<Integer> ids = JSON.parseArray(dto.getStyle().get("ids").toString(),Integer.class);
                if (CollectionUtils.isNotEmpty(ids)){
                    List<StoreProduct> storeProductList = storeProductService.list(new LambdaQueryWrapper<>(StoreProduct.class)
                            .in(StoreProduct::getId, ids).eq(StoreProduct::getIsShow, true).gt(StoreProduct::getStock, 0));
                    if (CollectionUtils.isNotEmpty(storeProductList)){
                        List<Integer> idsList = storeProductList.stream().map(StoreProduct::getId).collect(Collectors.toList());
                        //商户商品是否下架
                        List<StoreProductMer> productMerList = storeProductMerService.list(Wrappers.lambdaQuery(StoreProductMer.class)
                                .in(StoreProductMer::getProductId,idsList)
                                .eq(StoreProductMer::getIsNotShow,"1"));
                        List<Integer> productMerIds = productMerList.stream().map(StoreProductMer::getProductId).collect(Collectors.toList());
                        List<Integer> integerList = new ArrayList<>();
                        //商品展示需排序
                        ids.forEach(i -> {
                            if (idsList.contains(i) && !productMerIds.contains(i)){
                                integerList.add(i);
                            }
                        });
                        dto.getStyle().put("ids",integerList);
                    }

                }
            }
            homeStyleDTO.add(dto);
        }
        
        return CommonResult.success(homeStyleDTO);
    }

    @ApiOperation(value = "首页热门品牌")
    @GetMapping("/storeBrand/list")
    public CommonResult<Object> listEntity(@RequestParam(required = true) Integer type, @RequestParam(required = false) Integer isAdvice, HttpServletRequest request) {
        List<Integer> merShowBrand = storeBrandService.getMerShowBrand(getMerId(request),"");
        List<Integer> ids = channelStoreBrandConfigService.list(Wrappers.<ChannelStoreBrandConfig>lambdaQuery()
    			.select(ChannelStoreBrandConfig :: getBrandId)
    			.eq(ChannelStoreBrandConfig :: getMerId, getMerId(request))
    			.eq(null != isAdvice, ChannelStoreBrandConfig :: getIsAdvice, isAdvice)
                .orderByDesc(ChannelStoreBrandConfig :: getUpdateTime)
    			).stream().map(o -> o.getBrandId()).collect(Collectors.toList());
        ids.retainAll(merShowBrand);
    	if(CollectionUtils.isEmpty(ids)) {
    		return CommonResult.success();
    	}
    	List<StoreBrand> brands = storeBrandService.list(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand:: getType, type)
                .eq(StoreBrand :: getStatus, true)
                .in(StoreBrand :: getId, ids)
                );

    	brands.sort(((o1, o2) -> {
	        int io1 = ids.indexOf(o1.getId());
	        int io2 = ids.indexOf(o2.getId());
	        return io1 - io2;
	    }));
    	
    	return CommonResult.success(brands);
    }

    @ApiOperation(value = "通过专区id查询专区")
    @GetMapping(value = "/getZoneById/{id}")
    public CommonResult<StoreZone> getZoneById(@PathVariable("id") Integer id){
        return CommonResult.success(indexService.getZoneById(id));
    }

    @ApiOperation(value = "查询商户小程序收款信息")
    @GetMapping(value = "/applet/account")
    public CommonResult<AppletAccountRequest> getAppletAccount(HttpServletRequest httpServletRequest){
        return CommonResult.success(channelMerchantAccountService.getAppletAccount(getMerId(httpServletRequest)));
    }

    @ApiOperation(value = "获取批采配置")
    @GetMapping(value = "/picking/config")
    public CommonResult<PickIngConfigResponse> getPickingConfig(HttpServletRequest httpServletRequest){
        return CommonResult.success(channelMerchantService.getPickingConfig(getMerId(httpServletRequest)));
    }

    @ApiOperation(value = "广交会内容提交")
    @PostMapping(value = "/cantonFair")
    public CommonResult<Boolean> saveInfo(@RequestBody CantonFairInfoRequest request) {
        return CommonResult.success(cantonFairInfoService.savInfo(request));
    }

}



